package com.li.shop.controller;

import com.alibaba.fastjson.JSON;
import com.li.shop.domain.*;
import com.li.shop.redis.DynamicInfo;
import com.li.shop.redis.Phone;
import com.li.shop.redis.PhoneInfo;
import com.li.shop.redis.PhoneService;
import com.li.shop.service.*;
import com.li.shop.utils.JavaMailUtils;
import com.li.shop.utils.SearchUserResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.UUID;

//杨煦瑞做
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private ShopCardService shopCardService;
    @Autowired
    private UserAdressService userAdressService;
    @Autowired
    PhoneService phoneService;
    @Autowired
    private ProductGetService productGetService;

    @RequestMapping("/preLogin")
    public String hello() {
        return "before/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String userLogin(String userName, String password, HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = userService.login(userName, password);
        HttpSession session = request.getSession();


        if (user != null) {         //如果密码输入正确
            session.setAttribute("session_user", user);
            session.setAttribute("id", user.getuId());
            System.out.println(user.getuId());
            return "redirect:/user/loginafter";
        } else
            return "before/login";
    }

    @RequestMapping("/preRegister")
    public String preRegister() {
        return "before/register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String userRegister(String userName, String password, String password2, HttpSession session, HttpServletRequest request, HttpServletResponse response, Model model) throws UnsupportedEncodingException {
        String msg = null;
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String email = request.getParameter("email");
        String code = request.getParameter("code");
        session = request.getSession(false);

        if (userName.isEmpty()) {     //用户名或密码为空
            msg = "用户名或密码不能为空！";
            model.addAttribute("msg", msg);
            return "before/register";
        }
        if (password.isEmpty() || session == null || session.getAttribute("email") == null || session.getAttribute("code") == null) {
            msg = "邮箱不能为空！";
            model.addAttribute("msg", msg);
            return "before/register";
        } else {
            User user = userService.get(userName, password);
            String sessionEmail = (String) session.getAttribute("email");
            String sessionCode = (String) session.getAttribute("code");
            if (user == null && sessionEmail.equals(email) && sessionCode.equals(code)) {
                //即此用户还未被注册，可以注册
                //   User newUser=new User(" "," ",userName,password," "," "," "," "," ",0," ");
                User newUser = new User(userName, password, email);

                userService.insert(newUser);
//                System.out.println(newUser.getuId());

                return "before/login";
            } else {      //用户存在
                msg = "已存在此用户名或验证码不正确";
                model.addAttribute("msg", msg);
                System.out.println(msg);
                return "before/register";
            }
        }

    }

    @RequestMapping("/loginafter")
    public String loginafter(Model model, HttpSession session) {
        User user= (User) session.getAttribute("session_user");
        session.setAttribute("session_user", user);

        List<Product> product = productService.listAll();
        model.addAttribute("product", product);
        List<Dictionary> dict = dictionaryService.list();
        model.addAttribute("dictionary", dict);
        //拿到种类对应的商品种类
        List<Dictionary> d = dictionaryService.findAll();
        model.addAttribute("d", dict);
        //根据u_id拿到当前用户的购物车中的商品的数量
        String id = session.getAttribute("id").toString();
        List<Shopcard> shopcards = shopCardService.searchgoods(id);
        int productnum = 0;
        for (int i = 0; i < shopcards.size(); i++) {
            productnum += Integer.parseInt(shopcards.get(i).getPnum());
        }
        System.out.println("当前购物车中的数量为" + productnum);
        session.setAttribute("productnum", productnum);


        List<Product> products = productService.getAll();
        Product product1 = products.get(0);
        Product product2 = products.get(1);
        Product product3 = products.get(2);
        Product product4 = products.get(3);
        List<Phone> phones = Arrays.asList(
                new Phone(1, product1.getProductName()),
                new Phone(2, product2.getProductName()),
                new Phone(3, product3.getProductName()),
                new Phone(4, product4.getProductName()
                ));
        for (Phone phone : phones) {
            int ranking = phoneService.phoneRank(phone.getId()) + 1;
            phone.setRanking(ranking == 0 ? "榜上无名" : "销量排名：" + ranking);

        }

        model.addAttribute("phones", phones);
        //view.addObject("phones",phones);
        List<PhoneInfo> phbList = phoneService.getPhbList();
        List<DynamicInfo> dynamicList = phoneService.getBuyDynamic();
        // view.addObject("dynamicList", dynamicList);
        model.addAttribute("dynamicList", dynamicList);
        model.addAttribute("phbList", phbList);

        Jedis j = Redis.getRedis();
        String str=j.get("json");
        ProductGet p=productGetService.selectByid(JSON.parseArray(str).get(0).toString());
        ProductGet p1=productGetService.selectByid(JSON.parseArray(str).get(1).toString());
        ProductGet p2=productGetService.selectByid(JSON.parseArray(str).get(2).toString());
        ProductGet p3=productGetService.selectByid(JSON.parseArray(str).get(3).toString());
        model.addAttribute("json1",p);
        model.addAttribute("json2",p1);
        model.addAttribute("json3",p2);
        model.addAttribute("json4",p3);
        return "before/loginsuccess";
    }

    @RequestMapping("/loginbefore")
    public String loginbefore(Model model, HttpSession session) {
        List<Product> product = productService.listAll();
        model.addAttribute("product", product);
        List<Dictionary> dict = dictionaryService.list();
        model.addAttribute("dictionary", dict);
        //拿到种类对应的商品种类
        List<Dictionary> d = dictionaryService.findAll();
        model.addAttribute("d", dict);
//        //根据u_id拿到当前用户的购物车中的商品的数量
//        String id=session.getAttribute("id").toString();
//        List<Shopcard> shopcards = shopCardService.searchgoods(id);
//        int productnum = 0;
//        for (int i = 0; i < shopcards.size(); i++) {
//            productnum += Integer.parseInt(shopcards.get(i).getPnum());
//        }
//        System.out.println("当前购物车中的数量为" + productnum);
//        session.setAttribute("productnum", productnum);


        List<Product> products = productService.getAll();
        Product product1 = products.get(0);
        Product product2 = products.get(1);
        Product product3 = products.get(2);
        Product product4 = products.get(3);
        List<Phone> phones = Arrays.asList(
                new Phone(1, product1.getProductName()),
                new Phone(2, product2.getProductName()),
                new Phone(3, product3.getProductName()),
                new Phone(4, product4.getProductName()
                ));
        for (Phone phone : phones) {
            int ranking = phoneService.phoneRank(phone.getId()) + 1;
            phone.setRanking(ranking == 0 ? "榜上无名" : "销量排名：" + ranking);

        }

        model.addAttribute("phones", phones);
        //view.addObject("phones",phones);
        List<PhoneInfo> phbList = phoneService.getPhbList();
        List<DynamicInfo> dynamicList = phoneService.getBuyDynamic();
        // view.addObject("dynamicList", dynamicList);
        model.addAttribute("dynamicList", dynamicList);
//        view.addObject("phbList", phbList);
        model.addAttribute("phbList", phbList);
        return "before/home";
    }


    //进入用户详情
    @GetMapping("/details")
    public String userDetails(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();

        User session_user = (User) session.getAttribute("session_user");


        model.addAttribute("session_user", session_user);
        return "before/information";
    }

    //用户信息修改
    @PostMapping("/updateInfo")
    public String updateUserInfo(@RequestParam("userName") String userName, @RequestParam("userPassword") String password, @RequestParam("address") String address,
                                 @RequestParam("phone") String phoneNum, @RequestParam("email") String email, HttpServletRequest request, Model model) throws IOException {

        HttpSession session = request.getSession();
        User session_user = (User) session.getAttribute("session_user");

        session_user.setUserName(userName);
        session_user.setUserPassword(password);
        session_user.setAddress(address);
        session_user.setPhone(phoneNum);
        session_user.setEmail(email);
        userService.update(session_user);
        //未解决问题：必须退到preLogin刷新，否则无法跳转到
//        return "before/information";
        return "redirect:/user/details";
    }

    //用户头像修改
    @PostMapping("/headPicModify")
    public String modifyUserHeadPic(HttpServletRequest request, @RequestParam("file") MultipartFile file, Model model) throws IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("session_user");
//        System.out.println("用户名为：   "+user.getUserName());

        if (file != null) {                                 //前端获得的file不为空
            user.setFileContent(file.getBytes());
            user.setFileName(file.getOriginalFilename());
            user.setFileSize(new BigDecimal(file.getSize()));
            user.setFileContentType(file.getContentType());
        }
        Files.write(Paths.get("E:", "myFile", user.getuId() + ".jpg"), file.getBytes());     //在E盘myFile文件夹下面建立一个以用户id为名.jpg为后缀的文件

        user.setUpic(user.getuId() + ".jpg");

//        System.out.println("原文件名为：    "+user.getFileName());
//        System.out.println("用户id为：   "+user.getuId());
//        System.out.println("用户upic为：   "+user.getUpic());


//        int updated =userService.saveUser(user);
        userService.update(user);
        model.addAttribute("userPic", user.getuId());

//        return "before/information";
        return "redirect:/user/details";
    }

    //图片显示
    @RequestMapping(value = "list", method = RequestMethod.GET)


    //此方法不使用
    @GetMapping("/download")
    public ResponseEntity<Resource> download(@RequestParam("id") String id) {
        User user = userService.findUserByPrimaryKey(id);
        return ResponseEntity.ok()
                .contentLength(user.getFileSize().longValue())
                .contentType(MediaType.parseMediaType(user.getFileContentType()))
                .body(new ByteArrayResource(user.getFileContent()));

    }

    //    用户验证码（ajax传来的）
    @RequestMapping(value = "registerAuthCode", method = RequestMethod.POST)
    public void registerAuthCode(Admin admin, HttpSession session, HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String email = request.getParameter("email");
        Random rm = new Random();
        String code = "";
        for (int i = 0; i < 4; i++) {
            int num = rm.nextInt(26) + 65;
            code += (char) num;
        }
        int res = JavaMailUtils.sendEmail(new String[]{
                email //这里就是一系列的收件人的邮箱了
        }, "商城邮箱验证", "欢迎注册商城后台，您的验证码是 <br />" + code);
        session = request.getSession(true);
        session.setAttribute("code", code);
        session.setAttribute("email", email);
        session.setMaxInactiveInterval(60);
        //adminService.add(admin);
    }


    //王志文
    @RequestMapping(value = "/searchuser", method = RequestMethod.GET)
    public String userPage(Model model, Integer pageSize, Integer pageNum) {
        //TODO: Add user search result
        //普通显示
        // List<user> Users = userService.listUser( pageSize,pageNum);
        //model.addAttribute("users", users);
        //return "user-list-bak";//普通页面
        //return "user-list";//adminLTE页面
        return "/back/user-list";
    }

    //分页显示
    @GetMapping("/api/searchuser")
    @ResponseBody//需要返回json数据
    public SearchUserResponse searchUser(Integer pageNum, Integer pageSize, String keyword) {
        return userService.listUser(pageSize, pageNum, keyword);
    }

    @RequestMapping(value = "/adduser", method = RequestMethod.GET)
    public String addUserPage(Model model) {
        model.addAttribute("user", new User());
        return "/back/user-add";
    }

    @GetMapping("/edituser")
    public String editUserPage(@RequestParam("id") String id, Model model) {
        User user = userService.findUserByPrimaryKey(id);
        model.addAttribute("user", user);
        return "/back/user-add";
    }

    //    @RequestMapping(value = "/adduser", method = RequestMethod.POST)
//    public String saveUser(User user) {
//        int updated = userService.saveUser(user);
//        return "redirect:/user/searchuser";
//    }
    @RequestMapping(value = "/adduser", method = RequestMethod.POST)
    public String saveUser(User user, @RequestParam("file") MultipartFile multipartFile, Model model) throws IOException {
        String filename = multipartFile.getOriginalFilename();
        String sname = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID() + sname;
        String filepath = "E:/myFile/";
        multipartFile.transferTo(new File(filepath + filename));
        user.setUpic("/myFile/" + filename);
        int updated = userService.saveUser(user);
        return "redirect:/user/searchuser";
    }

    @RequestMapping(value = "/deleteuser", method = RequestMethod.GET)
    //@ResponseBody//需要返回json数据 @RequestParam("id") @PathVariable("id")
    public String deleteUser(@RequestParam("id") String id) {
        //var mymessage = confirm("确认删除嘛？");
        //if (mymessage == true) {
        int deleted = userService.deleteUserByPrimaryKey(id);

        // return deleted > 0;
        //return "redirect:/backadminuser/searchuser";//get请求不能用重定向
        return "/back/user-list";
        //return "redirect:/backadminuser/deleteuser";
    }

    @GetMapping("/editadr")//添加wzw
    public String editUserAdrPage(@RequestParam("id") String id, Model model) {
        UserAdress userAdress = userAdressService.findUserAdressByPrimaryKey(id);
        model.addAttribute("userAdress", userAdress);
        return "/back/useradr-add";
    }

    //    @RequestMapping(value = "/adduser", method = RequestMethod.POST)
//    public String saveUser(User user) {
//        int updated = userService.saveUser(user);
//        return "redirect:/user/searchuser";
//    }


    @RequestMapping(value = "/updateadr", method = RequestMethod.POST)//添加
    public String updateAdr(UserAdress userAdress, Model model) {
        //model.addAttribute("userAdress" userAdress);
        String uid = userAdress.getuId();
        String phone=userAdress.getPhone();
        System.out.println("woshi" + uid);
        String adr = userAdress.getAddress();
        System.out.println("woshi" + adr);
        model.addAttribute("uid", uid);
        model.addAttribute("adr", adr);
        User user=new User();
        user.setuId(uid);
        user.setAddress(adr);
        int updated = userService.updateUserById(user);
        return "redirect:/order/made";
    }
  @RequestMapping("/logout")
    public String logout(HttpSession session)
  {
      session.invalidate();
      return "redirect:/user/loginbefore";
  }
}
